package com.example.mybatis.demo1.Controller;

import com.example.mybatis.demo1.model.User;
import com.example.mybatis.demo1.common.ResultAjax;
import com.example.mybatis.demo1.Service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@ResponseBody
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    //获取所有user
    @RequestMapping("/getAll")
    public List<User> getAll(){
        System.out.println("getAll方法执行！");
        return userService.getAll();
    }
    //添加用户！

    @RequestMapping(value = "/adduser",method = RequestMethod.POST)
    public ResultAjax addUser(@RequestBody User user){
        return ResultAjax.succ(userService.addUser(user));
    }
    //添加用户！,并返回新自增的id
    @RequestMapping(value = "/adduser2",method = RequestMethod.POST)
    public ResultAjax addUser2(@RequestBody User user){
        return ResultAjax.succ(userService.addUser2(user));
    }

    //下面这种方式是在方法里面进行验证，这就意味着多个方法里面要写重复的验证代码！
    //我们可以采用AOP的思想来解决这个问题！————拦截器！
    @RequestMapping("/login")
    public ResultAjax login(HttpServletRequest request) {
        //怎么添加session来这！？？？
        return ResultAjax.succ("登录成功！");
    }

    @RequestMapping("/reg")
    public ResultAjax reg(HttpServletRequest request) {
        //怎么添加session来这！？？？
        return ResultAjax.succ("注册页面！");
    }


    //空指针异常测试！
    @RequestMapping("/test")
    public ResultAjax test() {
        Object obj = null;
        int i = obj.hashCode();
        return ResultAjax.succ("Hello,User Index.");
    }

    //空指针异常测试！
    @RequestMapping("/test2")
    public int test2() {
        int a=1;
        return a;
    }

    @RequestMapping("/test3")
    public String test3() {
        return "123";
    }




    //学习事务回滚
    @Transactional(propagation = Propagation.REQUIRED)
    @RequestMapping("/add1")
    public int add1(){
        int ret=userService.add1();
        userService.add2();
        return ret;

    }


}

//1，@Resource   和    @Autowired  区别及用法！
